from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError


# 审批流类
class Workflow(models.Model):
    _inherit = 'sb.workflow'

    # 关联销售单据
    purchase_order_id = fields.Many2one('purchase.order', string="Related Documents", ondelete="cascade")
    purchase_order_line_ids = fields.One2many('purchase.order.line', related="purchase_order_id.order_line")
    partner_id = fields.Many2one('res.partner', string="Supplier", related='purchase_order_id.partner_id')
    currency_id = fields.Many2one('res.currency', string="Currency", related='purchase_order_id.currency_id')
    purchase_requisition_id = fields.Many2one('purchase.requisition', string="Purchase Requisition", ondelete="cascade")
    pr_line_ids = fields.One2many('purchase.requisition.line.workflow', 'workflow_id')
    workflow_type = fields.Selection(selection_add=[
        ('purchase', 'Purchasing'),
        ('purchase_requisition', 'Purchase Requisition')
    ], ondelete={'activity': 'cascade'})
    requisition_form_ref = fields.Char(string="Requisition Form Ref", compute='_compute_requisition_form_ref')
    pr_product_categ_id = fields.Many2one('product.category', string="Product Category",
                                          related='purchase_requisition_id.product_categ_id')

    # 采购单相关信息


    equipment_id = fields.Many2one('equipment.requisition', string="Equipment Requisition", ondelete="cascade")
    equipment_user_id = fields.Many2one('res.users', string="Requisition User", related='equipment_id.user_id')
    equipment_department_id = fields.Many2one('hr.department', string="Requisition Department",
                                              related='equipment_id.department_id')
    equipment_type = fields.Selection([('engineering', 'Engineering'),
                                       ('equipment', 'Equipment')], related='equipment_id.type')
    equipment_name = fields.Char(string="Equipment Name", related='equipment_id.equipment_name')
    equipment_type_id = fields.Many2one('equipment.type', string="Equipment Type", related='equipment_id.equipment_type_id')
    equipment_qty = fields.Integer(string="Equipment Qty", related='equipment_id.equipment_qty')
    equipment_date = fields.Date(string="Equipment Date", related='equipment_id.date')
    equipment_remark = fields.Text(string="Equipment Remark", related='equipment_id.remark')
    equipment_description = fields.Text(string="Equipment Description", related='equipment_id.description')

    def _compute_requisition_form_ref(self):
        for rec in self:
            rec.requisition_form_ref = 'sb_workflow_purchase.purchase_requisition_view_form'

    @api.constrains('purchase_requisition_id')
    def _constrains_purchase_requisition_id(self):
        for rec in self:
            if rec.purchase_requisition_id:
                pr_workflow = []
                for line in rec.purchase_requisition_id.pr_line_ids:
                    if not line.product_id:
                        continue
                    pr_workflow.append((0, 0, {
                        'pr_line': line.id,
                        'parent_id': line.parent_id.id,
                        'unit_price': line.unit_price,
                    }))
                rec.write({'pr_line_ids': [(5, 0)]})
                rec.write({'pr_line_ids': pr_workflow})


class WorkflowItem(models.Model):
    _inherit = 'sb.workflow.item'
    _order = 'audit_level asc,id desc'

    pr_product_categ_id = fields.Many2one('product.category', string="Product Category",
                                          related='sb_workflow_id.pr_product_categ_id')
    partner_id = fields.Many2one('res.partner', string="Supplier", related='sb_workflow_id.partner_id')
    currency_id = fields.Many2one('res.currency', string="Currency", related='sb_workflow_id.currency_id')
    po_amount_total = fields.Monetary(string="Purchase Order Total", related="sb_workflow_id.purchase_order_id.amount_total")


class RequisitionLineWorkFlow(models.Model):
    _name = 'purchase.requisition.line.workflow'
    _description = 'Purchase Requisition Line Workflow'

    pr_line = fields.Many2one('purchase.requisition.line', string='Purchase Requisition Line', ondelete="cascade")
    workflow_id = fields.Many2one('sb.workflow', string="Workflow", ondelete="cascade")
    product_id = fields.Many2one('product.template', related='pr_line.product_id', store=True)
    default_code = fields.Char('Default Code', related='product_id.default_code', store=True)
    product_qty = fields.Float('Quantity', digits='Product Unit of Measure', related='pr_line.product_qty', store=True)
    product_uom_id = fields.Many2one('uom.uom', 'Unit of purchase', related='pr_line.product_uom_id', store=True)
    domain_parent_ids = fields.Many2many('res.partner', string='supplier', compute='get_domain_partner')
    parent_id = fields.Many2one('res.partner', string='supplier')
    unit_price = fields.Float('Unit Price', digits='Product Unit of Measure')
    requirement_date = fields.Date('requirement date', related='pr_line.requirement_date', store=True)

    @api.depends('product_id')
    def get_domain_partner(self):
        for record in self.sudo():
            domain_parent_ids = record.product_id.seller_ids.mapped('partner_id.id')
            record.domain_parent_ids = domain_parent_ids
            if record.parent_id:
                continue
            if len(domain_parent_ids) == 1:
                record.parent_id = domain_parent_ids[0]
            else:
                record.parent_id = False

    @api.onchange('parent_id', 'unit_price')
    def onchange_unit_price(self):
        """
        更改单价会写请购单
        """
        self = self.sudo()
        for record in self:
            if record.unit_price < 0:
                raise ValidationError(_('Unit Price must be greater than 0'))
            record.pr_line.write({'unit_price': record.unit_price})
